package org.example.groupwarehouse.controller;

import jakarta.servlet.http.HttpSession;
import org.example.groupwarehouse.entity.Admin;
import org.example.groupwarehouse.entity.Users;
import org.example.groupwarehouse.service.admin.AdminService;
import org.example.groupwarehouse.service.CaptchaService;
import org.example.groupwarehouse.service.UserService;
import org.example.groupwarehouse.service.login.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 用户控制器
 * 处理用户登录、注册、个人信息管理等功能
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private LoginStrategy loginStrategy;
    @Autowired
    private CaptchaService captchaService;
    @GetMapping("/login")
    public String login(){
        return "login";
    }
    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password,
                        @RequestParam("captcha") String captcha,
                        HttpSession session,
                        RedirectAttributes redirectAttributes) {
        // 验证验证码
        if (!captchaService.validateCaptcha(session, captcha)) {
            redirectAttributes.addFlashAttribute("error", "验证码错误");
            return "redirect:/user/login";
        }

        Users user = loginStrategy.login(account, password);
        //区分时普通用户登录还是管理员登录
        if(user == null){
            //可能是管理员登录或登录失败
            if(account.equals("admin")){
                //尝试管理员登录
                Admin admin = adminService.login(account, password);
                if(admin != null){
                    //管理员登录成功
                    session.setAttribute("loginUser", admin);
                    session.setAttribute("isAdmin", true);
                    return "redirect:/";
                }
            }
            //登录失败
            redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
            return "redirect:/user/login";
        }else{
            session.setAttribute("loginUser", user);
            session.setAttribute("isAdmin", false);
            return "redirect:/";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        session.removeAttribute("isAdmin");
        return "redirect:/user/login";
    }
    @GetMapping("/register")
    public String register(){
        return "register";
    }

    @PostMapping("/register")
    public String register(
            @RequestParam String account,
            @RequestParam String password,
            @RequestParam String email,
            @RequestParam String telphone,
            @RequestParam String url,
            @RequestParam String captcha,
            HttpSession session,
            RedirectAttributes redirectAttributes) throws Exception{
        // 验证验证码
        if (!captchaService.validateCaptcha(session, captcha)) {
            redirectAttributes.addFlashAttribute("error", "验证码错误");
            return "redirect:/user/register";
        }

        // 验证密码格式
        if (!password.matches("^[A-Z][A-Za-z0-9]{5,}$")) {
            redirectAttributes.addFlashAttribute("error", "密码格式不正确，必须以大写字母开头且至少6位");
            return "redirect:/user/register";
        }

        boolean re = userService.insertUser(account,password,email,telphone,url);
        if(re){
            //重定向到其他的页面
            redirectAttributes.addFlashAttribute("message", "注册成功，请登录");
            return "redirect:/user/login";
        }else{
            redirectAttributes.addFlashAttribute("error", "注册失败，请检查输入信息");
            return "redirect:/user/register";
        }
    }
    @PostMapping("/upload")
    public ResponseEntity<String> uploadAvatar(MultipartFile file) throws Exception {
        String url = userService.uplaodAvatar(file);
        return ResponseEntity.ok(url);
    }

    /**
     * 显示用户个人信息页面
     */
    @GetMapping("/profile")
    public String showProfilePage(HttpSession session) {
        // 检查用户是否已登录
        Users loginUser = (Users) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/user/login";
        }
        return "user_profile";
    }

    /**
     * 更新用户个人信息
     */
    @PostMapping("/updateProfile")
    public String updateProfile(
            @RequestParam("account") String account,
            @RequestParam("telphone") String telphone,
            @RequestParam("email") String email,
            @RequestParam("avatar") String avatar,
            @RequestParam("captcha") String captcha,
            HttpSession session,
            RedirectAttributes redirectAttributes) {

        // 检查用户是否已登录
        Users loginUser = (Users) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/user/login";
        }

        // 验证验证码
        if (!captchaService.validateCaptcha(session, captcha)) {
            redirectAttributes.addFlashAttribute("error", "验证码错误");
            return "redirect:/user/profile";
        }

        // 验证手机号格式（前端已验证，但后端也需验证）
        if (!telphone.matches("^1\\d{10}$")) {
            redirectAttributes.addFlashAttribute("error", "手机号格式不正确，必须是11位数字且以1开头");
            return "redirect:/user/profile";
        }
        
        // 验证邮箱格式（前端已验证，但后端也需验证）
        if (!email.matches("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$")) {
            redirectAttributes.addFlashAttribute("error", "邮箱格式不正确");
            return "redirect:/user/profile";
        }

        // 更新用户信息
        Users user = new Users();
        user.setAccount(account);
        user.setTelphone(telphone);
        user.setEmail(email);
        user.setAvatar(avatar);

        boolean success = userService.updateUserProfile(user);
        if (success) {
            // 更新成功，直接更新session中的用户信息
            // 获取当前session中的用户对象
            Users currentUser = (Users) session.getAttribute("loginUser");
            // 更新用户信息
            currentUser.setTelphone(telphone);
            currentUser.setEmail(email);
            currentUser.setAvatar(avatar);
            // 重新设置session中的用户信息
            session.setAttribute("loginUser", currentUser);
            redirectAttributes.addFlashAttribute("message", "个人信息更新成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "个人信息更新失败，请检查输入格式");
        }

        return "redirect:/user/profile";
    }

    /**
     * 更新用户密码
     */
    @PostMapping("/updatePassword")
    public String updatePassword(
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword,
            @RequestParam("confirmPassword") String confirmPassword,
            @RequestParam("captcha") String captcha,
            HttpSession session,
            RedirectAttributes redirectAttributes) {

        // 检查用户是否已登录
        Users loginUser = (Users) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/user/login";
        }

        // 验证验证码
        if (!captchaService.validateCaptcha(session, captcha)) {
            redirectAttributes.addFlashAttribute("passwordError", "验证码错误");
            return "redirect:/user/profile";
        }

        // 检查两次输入的密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            redirectAttributes.addFlashAttribute("passwordError", "两次输入的密码不一致");
            return "redirect:/user/profile";
        }
        
        // 先验证原密码是否正确
        String oldPasswordMd5 = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        Users user = userService.getUserByAccount(loginUser.getAccount());
        if (user == null || !user.getPassword().equals(oldPasswordMd5)) {
            redirectAttributes.addFlashAttribute("passwordError", "原密码不正确");
            return "redirect:/user/profile";
        }
        
        // 验证新密码格式
        if (!newPassword.matches("^[A-Z][A-Za-z0-9]{5,9}$")) {
            redirectAttributes.addFlashAttribute("passwordError", "新密码格式不正确，必须以大写字母开头，只能包含字母和数字，长度6-10位");
            return "redirect:/user/profile";
        }

        // 更新密码
        boolean success = userService.updatePassword(loginUser.getAccount(), oldPassword, newPassword);
        if (success) {
            redirectAttributes.addFlashAttribute("passwordMessage", "密码修改成功，请重新登录");
            // 密码修改成功后，清除登录状态，要求用户重新登录
            session.removeAttribute("loginUser");
            session.removeAttribute("isAdmin");
            return "redirect:/user/login";
        } else {
            redirectAttributes.addFlashAttribute("passwordError", "密码修改失败，系统错误");
            return "redirect:/user/profile";
        }
    }
}
